package com.zhangxiaofanfan.hotcode.first;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/partition-equal-subset-sum/?envType=study-plan-v2&envId=top-100-liked">416. 分割等和子集</a>
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode089 {
    public static void main(String[] args) {
        HotCode089 hotCode = new HotCode089();
        int[] nums = {18,17,18,11,15,4,13,11,9};
        System.out.println(hotCode.canPartition(nums));
    }

    Map<Integer, Boolean> map = new HashMap<>();
    public boolean canPartition(int[] nums) {
        int sum = Arrays.stream(nums).sum();
        if (nums.length == 1 || sum % 2 == 1) {
            return false;
        }
        int half = sum / 2;
        Arrays.sort(nums);
        return bfs(nums, 0, half);
    }

    public boolean bfs(int[] nums, int index, int sum) {
        if (sum == 0) {
            return true;
        }
        if (sum < 0 || index >= nums.length) {
            return false;
        }
        if (map.containsKey(sum)) {
            return map.get(sum);
        }
        while (index < nums.length) {
            boolean status = bfs(nums, index + 1, sum - nums[index]);
            // map.put(sum - nums[index], status);
            if (status) {
                return true;
            }
            index++;
        }
        // map.put(sum, false);
        return false;
    }
}